package com.terrynoya.fight.char
{
	import com.terrynoya.common.util.DisplayUtil;
	import com.terrynoya.fight.animations.IAnimationElement;
	import com.terrynoya.fight.animations.SpriteId;
	import com.terrynoya.fight.data.parser.sff.SpriteItem;
	import com.terrynoya.fight.data.parser.sff.SpriteMaker;
	import com.terrynoya.fight.emuns.Facing;
	import com.terrynoya.geom.MVector2D;
	
	import flash.display.Bitmap;
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.geom.Point;

	public class CharacterRender implements ICharaterRender
	{
		private var _spriteMaker:SpriteMaker;
		
		public static const SCALE_LEFT:MVector2D = new MVector2D(-1,1);
		public static const SCALE_RIGHT:MVector2D = new MVector2D(1,1);
		
		public function CharacterRender(spriteMaker:SpriteMaker)
		{
			this._spriteMaker = spriteMaker;
		}
		
		public function draw(entity:Entity,render:Sprite):void
		{
			var element:IAnimationElement = entity.animationManager.currentElement;
			var id:SpriteId = element.spriteId;
			var item:SpriteItem = this._spriteMaker.getSprite(id.groupId,id.imageId);
			if(item == null)
			{
				return;
			}
			DisplayUtil.clearChildren(render);
			
			var scale:MVector2D = this.getScaleByFacing(entity.facing);
			
			var src:Bitmap = Bitmap(item.view);
			var bmp:Bitmap = new Bitmap(src.bitmapData.clone())
			bmp.scaleX = scale.x;
			
			var pos:MVector2D = this.localToGlobal(MVector2D.fromPoint(item.info.axis),element.offset,entity);
			
			render.addChild(bmp);
			render.x = pos.x;
			render.y = pos.y;
		}
		
		/**
		 * 将人物图片坐标转换到舞台坐标 
		 * @param item
		 * @param character
		 * @return 
		 * 
		 */		
		private function localToGlobal(axis:MVector2D,offset:MVector2D,entity:Entity):MVector2D
		{
			var pos:MVector2D = entity.position;
			var scale:MVector2D = this.getScaleByFacing(entity.facing);
			var stageY:int = entity.engine.stage.height - entity.engine.camera.height + entity.engine.stage.zOffset
			var stageVec:MVector2D = new MVector2D(0,stageY);
			var globalPos:MVector2D = pos.add(stageVec);
			var cameraPos:MVector2D = entity.engine.globalToCamera(globalPos);
			var rlt:MVector2D = cameraPos.substract(axis.substract(offset).mutiply(scale));
			return rlt;
		}
		
		private function getScaleByFacing(facing:int):MVector2D
		{
			if(facing == Facing.LEFT)
			{
				return SCALE_LEFT;
			}
			else
			{
				return SCALE_RIGHT;
			}
		}
	}
}